import {
  getStyle
} from 'common/js/util'

/**
 * @author yang
 * @desc 滑动页面判断是否需要加载更改 混合指令 可以直接引用指令 v-load-more="loaderMore" loaderMore是一个方法
 */
export const loadMore = {
  directives: {
    'load-more': {
      bind: (el, binding) => {
        let windowHeight = window.screen.height;
        let height;
        let setTop;
        let paddingBottom;
        let marginBottom;
        let requestFram;
        let oldScrollTop;
        let scrollEl;
        let heightEl;
        let scrollReduce = 2;
        scrollEl = document.body;
        heightEl = el;

        el.addEventListener('touchstart', () => {
          height = heightEl.clientHeight;
          setTop = el.offsetTop;
          paddingBottom = getStyle(el, 'paddingBottom');
          marginBottom = getStyle(el, 'marginBottom');
        }, false)

        el.addEventListener('touchmove', () => {
          loadMore();
        }, false)

        el.addEventListener('touchend', () => {
          oldScrollTop = scrollEl.scrollTop;
          moveEnd();
        }, false)

        const moveEnd = () => {
          requestFram = requestAnimationFrame(() => {
            if (scrollEl.scrollTop != oldScrollTop) {
              oldScrollTop = scrollEl.scrollTop;
              moveEnd()
            } else {
              cancelAnimationFrame(requestFram);
              height = heightEl.clientHeight;
              loadMore();
            }
          })
        }

        const loadMore = () => {
          // 如果当前滚动的高度和窗口高度 大于 当前滚动元素的可视区高度和距离顶部高度 就触发函数 已经到达底部可以加载更改
          if (scrollEl.scrollTop + windowHeight >= height + setTop + paddingBottom + marginBottom - scrollReduce) {
            binding.value();
          }
        }
      }
    }
  }
}
